import { Button, Upload } from "antd";
import { Component } from "react";
import request from "@/utils/request";

import style from "./index.module.scss";

const UploadButton = <div className={style.button}>请选择头像</div>;

interface IProps {
  url?: string;
  onChange?: (value: string) => void;
}

export default class AvatarUpload extends Component<IProps> {
  render() {
    const {
      props: { url, onChange },
    } = this;

    return (
      <Upload
        className={style.box}
        showUploadList={false}
        customRequest={async (options) => {
          // file 属性，是我们的文件对象
          const file = options.file;
          // 调用接口
          const resp = await request<string>({
            url: "/app/base/comm/upload",
            method: "POST",
            data: { file },
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });

          // this.setState({ url: resp });
          onChange?.(resp);
        }}
      >
        {url ? (
          <div className={style.avatar}>
            <img src={url} />
            <div className={style.mask}>
              <Button
                onClick={(event) => {
                  event.stopPropagation();
                  // this.setState({ url: "" });
                  onChange?.("");
                }}
              >
                删除
              </Button>
            </div>
          </div>
        ) : (
          UploadButton
        )}
      </Upload>
    );
  }
}
